package com.imu.purse.api.controller.trade;

import com.alibaba.fastjson.JSON;
import com.egzosn.pay.ali.api.AliPayConfigStorage;
import com.egzosn.pay.ali.before.api.AliPayService;
import com.egzosn.pay.common.api.PayService;
import com.egzosn.pay.common.http.HttpConfigStorage;
import com.imu.common.exception.ErrorDesc;
import com.imu.common.exception.ErrorUtil;
import com.imu.common.utils.R;
import com.imu.common.validator.ValidatorUtils;
import com.imu.common.validator.group.AddGroup;
import com.imu.purse.api.controller.ApiAbstractController;
import com.imu.purse.modules.app.entity.ImuUserEntity;
import com.imu.purse.modules.app.service.ImuUserService;
import com.imu.purse.modules.base.entity.SysConfigEntity;
import com.imu.purse.modules.base.service.SysConfigService;
import com.imu.purse.modules.trade.entity.LaaFundEntity;
import com.imu.purse.modules.trade.entity.LaaUsdtRechargeEntity;
import com.imu.purse.modules.trade.entity.YmbDetailEntity;
import com.imu.purse.modules.trade.entity.YmbWithdrawEntity;
import com.imu.purse.modules.trade.form.RechargeForm;
import com.imu.purse.modules.trade.form.UsdtchargeForm;
import com.imu.purse.modules.trade.form.YmbWithdrawForm;
import com.imu.purse.modules.trade.service.LaaFundService;
import com.imu.purse.modules.trade.service.LaaUsdtRechargeService;
import com.imu.purse.modules.trade.service.YmbDetailService;
import com.imu.purse.modules.trade.service.YmbWithdrawService;
import com.imu.security.SessionTokenProviderFactory;
import com.imu.utils.IDUtils;
import com.imu.utils.RSASignature;
import com.xiaoleilu.hutool.bean.BeanUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 私募接口
 * @author sunhongwei
 * @email sunhongwei@gmail.com
 * @date 2018-03-22 17:27
 */
@RestController
@RequestMapping("/api/usdt")
@Api(tags="USDT接口")
public class ApiUSDTController extends ApiAbstractController
{


    private PayService service = null;

    @Value("${alipay_appId}")
    private String appId;

    @Value("${alipay_appPrivateKey}")
    private String appPrivateKey;

    @Value("${alipay_alipayPulicKey}")
    private String alipayPulicKey;

    @Value("${alipay_serverUrl}")
    private String serverUrl;


    @PostConstruct
    public void init() {
        AliPayConfigStorage aliPayConfigStorage = new AliPayConfigStorage();
        aliPayConfigStorage.setPid("");
        aliPayConfigStorage.setAppId(appId);
        aliPayConfigStorage.setKeyPublic(alipayPulicKey);
        aliPayConfigStorage.setKeyPrivate(appPrivateKey);
        aliPayConfigStorage.setNotifyUrl(serverUrl);
        aliPayConfigStorage.setReturnUrl(serverUrl);
        aliPayConfigStorage.setSignType("签名方式");
        aliPayConfigStorage.setSeller("收款账号");
        aliPayConfigStorage.setInputCharset("utf-8");
        //是否为测试账号，沙箱环境
        aliPayConfigStorage.setTest(true);

        // service = new AliPayService(aliPayConfigStorage);
        //请求连接池配置
        HttpConfigStorage httpConfigStorage = new HttpConfigStorage();
        //最大连接数
        httpConfigStorage.setMaxTotal(20);
        //默认的每个路由的最大连接数
        httpConfigStorage.setDefaultMaxPerRoute(10);
        service =  new AliPayService(aliPayConfigStorage, httpConfigStorage);

    }

	@PostMapping("charge")
    @ApiOperation(value = "充值",notes = "充值说明")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", dataType="String",    name = "X-IMU-SECRET",  value = "密钥",  required = true),
            @ApiImplicitParam(paramType = "header", dataType="String",    name = "X-IMU-SESSION", value = "会话",  required = true),
            @ApiImplicitParam(paramType = "header", dataType="String",    name = "X-IMU-SIGN", 	  value = "签名",  required = true),
            @ApiImplicitParam(paramType = "body",   dataType="RechargeForm", name = "form", 	  value = "充值",	  required = true)
    })
    public R rcharge(HttpServletRequest request, @RequestHeader("X-IMU-SECRET") String secret, @RequestHeader("X-IMU-SESSION") String token, @RequestHeader("X-IMU-SIGN") String sign, @RequestBody UsdtchargeForm form) {
        //表单校验
        ValidatorUtils.validateEntity(form, AddGroup.class);

        //校验USDT的价格
        SysConfigEntity sysConfigEntity = sysConfigService.findByKey("USDT");
        if(form.getMoney().compareTo(form.getNum().multiply(new BigDecimal(sysConfigEntity.getValue())))!=0)
            return ErrorUtil.errorMesg(request, ErrorDesc.SESSION_EMPTY);

        //判断Session 是否存在
        String uid = SessionTokenProviderFactory.getSessionTokenProvider().getUserId(secret, token);
        if (StrUtil.isBlank(uid)) {
            return ErrorUtil.errorMesg(request, ErrorDesc.SESSION_EMPTY);
        }
        
        //校验签名信息
        if (!RSASignature.verifySign(JSON.toJSONString(form), sign, this.pubKey)) {
            return ErrorUtil.errorMesg(request, ErrorDesc.SIGN_VERIFY_ERR);
        }

        //根据id获取该用户的手机号码
        ImuUserEntity user = userService.findById(Long.valueOf(uid));
        if(null == user || StrUtil.isBlank(user.getPhone())){
            return ErrorUtil.errorMesg(request,ErrorDesc.GET_USER_ERR);
        }

        //保存记录
        LaaUsdtRechargeEntity laaUsdtRechargeEntity = new LaaUsdtRechargeEntity();
        laaUsdtRechargeEntity.setUserId(user.getId());
        laaUsdtRechargeEntity.setMoney(form.getMoney());
        laaUsdtRechargeEntity.setNum(form.getNum());
        laaUsdtRechargeEntity.setPrice(new BigDecimal(sysConfigEntity.getValue()));
        laaUsdtRechargeEntity.setOrderNo(IDUtils.getOrder());
        laaUsdtRechargeEntity.setPayType(form.getPaytype()); //1支付宝
        laaUsdtRechargeEntity.setThirdOrderNo(""); //第三方流水
        laaUsdtRechargeEntity.setStatus(1); //0:失败，1：成功，2：补发，3：废弃
        laaUsdtRechargeEntity.setFinishTime(new Date());
        laaUsdtRechargeEntity.setResultMsg("");
        laaUsdtRechargeEntity.setRemark(form.getRemark());
        laaUsdtRechargeEntity.setUpdateUser(user.getId());
        laaUsdtRechargeService.save(laaUsdtRechargeEntity);

        LaaFundEntity laaFundEntity = new LaaFundEntity();
        laaFundEntity.setUserId(user.getId());
        List<LaaFundEntity> laaFundEntitys = laaFundService.queryList(laaFundEntity);
        if(null == laaFundEntitys || laaFundEntitys.size() <=0){ //表里没数据 需要重新插入
            laaFundEntity.setLaa(new BigDecimal(0));
            laaFundEntity.setLaaFronze(new BigDecimal(0));
            laaFundEntity.setLaaLock(new BigDecimal(0));
            laaFundEntity.setUsdt(form.getMoney());
            laaFundEntity.setUsdtLock(new BigDecimal(0));
            laaFundEntity.setUsdtFronze(new BigDecimal(0));
            laaFundService.save(laaFundEntity);
        }else{ //增加
            laaFundEntity = laaFundEntitys.get(0);
            laaFundEntity.setUsdt(laaFundEntity.getUsdt().add(form.getNum()));
            laaFundService.saveUpdate(laaFundEntity);
        }


        return R.ok(1);
    }
    
    @GetMapping("rcharge")
    @ApiOperation(value = "查询充值",notes = "查询充值说明")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", dataType="String",    name = "X-IMU-SECRET",  value = "密钥",  required = true),
            @ApiImplicitParam(paramType = "header", dataType="String",    name = "X-IMU-SESSION", value = "会话",  required = true),
            @ApiImplicitParam(paramType = "query", dataType="Integer",    name = "page",  value = "页码",  required = true),
            @ApiImplicitParam(paramType = "query", dataType="Integer",    name = "limit", value = "记录",  required = true)
    })
    public R rcharge(HttpServletRequest request, @RequestHeader("X-IMU-SECRET") String secret, @RequestHeader("X-IMU-SESSION") String token, Integer page, Integer limit) {
        //判断Session 是否存在
        String uid = SessionTokenProviderFactory.getSessionTokenProvider().getUserId(secret, token);
        
        if (StrUtil.isBlank(uid)) 
        {
            return ErrorUtil.errorMesg(request, ErrorDesc.SESSION_EMPTY);
        }

        LaaUsdtRechargeEntity entity = new LaaUsdtRechargeEntity();
        entity.setUserId(Long.valueOf(uid));
        entity.setPage(page);
        entity.setLimit(limit);
        return R.ok(1).put("data", laaUsdtRechargeService.queryList(entity));
    }


    @Autowired
    private LaaFundService laaFundService;

    @Autowired
    private LaaUsdtRechargeService laaUsdtRechargeService;

	@Autowired
	private ImuUserService userService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private SysConfigService sysConfigService;
	
    /****
     *公钥解密
     */
    @Value("${app.pay.pub-key}")
    private String pubKey;
}
